package com.cr.admin.base.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import com.cr.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaService {

    private static final String CAPTCHA_CACHE_KEY = "captcha:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Map<String, Object> generateCaptcha(){
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(100, 40, 4);
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(CAPTCHA_CACHE_KEY+key,gifCaptcha.getCode(), 2, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("captchaKey", key);
        map.put("captchaBase64", gifCaptcha.getImageBase64Data());
        return map;
    }

    public void checkCaptcha(String captchaKey, String captcha){
        Object value = redisTemplate.opsForValue().get(CAPTCHA_CACHE_KEY + captchaKey);
        redisTemplate.delete(CAPTCHA_CACHE_KEY + captchaKey);
        if (Objects.isNull(value)){
            throw new ServiceException("验证码已过期");
        }
        if (value.toString().equalsIgnoreCase(captcha)){
            throw new ServiceException("验证码错误");
        }
    }
}
